<template>
  <div calss='article-list' @scroll="scroll" ref="refScroll">
<van-pull-refresh v-model="isLoading" @refresh="onRefresh">
  <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad">
      <van-cell
        v-for="item in articleList"
        :key="item.art_id"
        @click="$router.push('/article/'+item.art_id)"
        >
       <template #title>
          <span class="custom-title">{{item.title}}</span>
          <van-grid v-if="item.cover.images"
          :column-num="item.cover.images.length">
            <van-grid-item  v-for="(pic,index) in item.cover.images" :key="index" v-lazy='pic'>
              <van-image :src="pic"/>
            </van-grid-item>
          </van-grid>
          <div class="meta">
            <span>{{ item.aut_name }}</span>
            <span>{{ item.comm_count }}评论</span>
            <span>{{ item.pubdate|relative }}</span>
            <van-icon name="cross" v-if="$store.state.user.tokenInfo" @click.stop="handle(item.art_id)"/>
          </div>
        </template>

      </van-cell>
    </van-list>
</van-pull-refresh>

  </div>
</template>

<script>
import { reqGetArticleList } from '@/api/channels'
export default {
  props: ['id'],
  created () {
    this.$eventBus.$on('del-article', obj => {
      const { articleId, channelId } = obj
      if (channelId === this.id) this.articleList = this.articleList.filter(item => item.art_id !== articleId)
      // console.log(obj)
    })
  },
  data () {
    return {
      articleList: [],
      timestamp: '',
      loading: false,
      finished: false,
      isLoading: false,
      page: 1,
      scrollTop: ''
    }
  },
  methods: {
    // 上拉加载
    async onLoad () {
      if (!this.timestamp) this.timestamp = +new Date()
      const res = await reqGetArticleList(this.id, this.timestamp)
      this.timestamp = res.data.pre_timestamp
      const arr = res.data.results
      this.articleList = [...this.articleList, ...arr]
      this.loading = false
      if (this.articleList.length >= 40) {
        this.finished = true
      }
    },
    // 下拉刷新
    async onRefresh () {
      const res = await reqGetArticleList(this.id, +new Date())
      this.timestamp = res.data.pre_timestamp
      this.articleList = res.data.results
      this.$toast.success('刷新成功')
      this.isLoading = false
    },
    handle (id) {
      this.$emit('handle', id)
    },
    scroll (e) {
      this.scrollTop = e.target.scrollTop
    }
  },
  activated () {
    this.$refs.refScroll.scrollTop = this.scrollTop
  }
}
</script>

<style lang='scss' scoped>
 .meta {
    span{
      margin-right: 10px;
      color:rgb(177, 177, 177);
      font-size: 12px;
    }
  }
  .van-icon{
    float: right;
  }
  .article-list {
  height: 100%;
  overflow: auto;
}
</style>
